/*
	Copyright (c) 2008, Grant Jones <grant@podtronics.com>.
	All rights reserved.

	Redistribution and use in source and binary forms, with or
	without modification, are permitted provided that the following
	conditions are met:

		Redistributions of source code must retain the above copyright
		notice, this list of conditions and the following disclaimer.
		
		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in
		the documentation and/or other materials provided with the
		distribution.
		
		Neither the name of the gxjones.com nor the names of its
		contributors may be used to endorse or promote products derived
		from this software without specific prior written permission.
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
	OF THE POSSIBILITY OF SUCH DAMAGE.
	
	http://www.opensource.org/licenses/bsd-license.php
*/

/*
 *  edb_msg_parser.c
 *  scatterd
 *
 *  Created by Grant Jones on 2/24/08.
 *
 */

#include "edb_main.h"
#include "edb_msg_parser.h"
#include "edb_msg_tokenize.h"
#include "strmap.h"

#include "edb_domain.h"
#include "edb_domain_select.h"
#include "edb_domain_insert.h"
#include "edb_domain_delete.h"

void edbBeginParse( edbParseContext *ctx, int explain ) { }

void edbFinishCoding( edbParseContext *ctx ) { }

void edbDeleteFrom( edbParseContext *ctx, Token *from_name, Expr *where, AttrList *what )
{
//	printf("edbDeleteFrom\n");
	
	edb_domain_ref_t *dref;
	
	dref = edb_domain_use( ctx->pcs, ctx->out_items->mempool, (const char *)from_name->z, from_name->n );
	if(!dref )
	{
		/* TODO: raise error */
		return;
	}
	
	edb_domain_delete( dref, what, where, ctx->out_items );
	
	edb_domain_release(ctx->pcs, dref);
	
}

void edbCreateDomain( edbParseContext *ctx, Token *name, AttrList *default_attrs )
{
#ifdef DUMP_ARGS
	printf("edbStartCreateDomain : ");	
	print_len( name->z, name->n );
	if( default_attrs )
	{
		printf("; default_attrs count: %d\n", default_attrs->num);
		
		cmapEnumStruct e;
		int key;
		void *data;
		cmap_enum( default_attrs, &e );
		while( data = cmap_enum_next( &e, &key ) )
		{
			AttrValue *av = data;
			
			printf("key: ");
			print_len( av->key.z, av->key.n );
			printf("; value: ");
			print_len( av->value.z, av->value.n );
			printf("\n");		
		}	
	}
	else
	{
		printf("; no default attributes\n");
	}
#endif
}

void edbDropDomain( edbParseContext *ctx, Token *name )
{
	/* TODO */
}

/* TODO: remove these */
void edbSyncDomainUp( edbParseContext *ctx, Token *name, Token *as_name )
{
/*	ctx->pcs->simpledb.syncup( &ctx->pcs->simpledb, (const char *)name->z, name->n );*/
}
void edbSyncDomainDown( edbParseContext *ctx, Token *name, Token *as_name )
{
/*	ctx->pcs->simpledb.syncdown( &ctx->pcs->simpledb, (const char *)name->z, name->n ); */

}
void edbSyncDomainDelete( edbParseContext *ctx, Token *name, Token *as_name )
{
/*	ctx->pcs->simpledb.delete( &ctx->pcs->simpledb, (const char *)name->z, name->n );*/
}

void edbSelect(edbParseContext *ctx, AttrList *selattrlist, Token *from_name, Expr *where_expr, void *groupby_arg, void *having_arg, AttrList *orderby_arg, AttrList *limit_arg)
{
	if(!from_name)
	{
		/* TODO: raise error */
		return;
	}
	
	edb_domain_ref_t *dref;
	
	dref = edb_domain_use( ctx->pcs, ctx->out_items->mempool, (const char *)from_name->z, from_name->n );
	if(!dref )
	{
		/* TODO: raise error */
		return;
	}
	
	edb_domain_select( dref, selattrlist, where_expr, NULL, NULL, orderby_arg, limit_arg, ctx->out_items );
	
	edb_domain_release(ctx->pcs, dref);
	
}

void edbInsert( edbParseContext *ctx, Token *name, AttrList *insert_values, Expr *where_expr )
{
	if(!insert_values)
	{
		printf("edbInsert missing values\n");
		return;
	}
#ifdef DUMP_ARGS	
	printf("edbInsert into \"");
	print_len( name->z, name->n );

	printf("\"\nvalue pair count: %d\n", insert_values->num);
#endif	
	
	edb_domain_ref_t *dref;
	
	dref = edb_domain_use( ctx->pcs, ctx->out_items->mempool, (const char *)name->z, name->n );
	if(!dref )
	{
		/* TODO: raise error */
		return;
	}
	
	if( !where_expr )
		edb_domain_insert_uncond( dref, insert_values, ctx->out_items );
	else
		edb_domain_insert( dref, insert_values, where_expr, ctx->out_items );
	
	
	edb_domain_release(ctx->pcs, dref);
	
}

/* Parse and interpret the preamble statement using the attributes from the
** items as necessary. There may be 0 or more items, the statement is run
** for each input item.
** The preamble must be NULL terminated. */

cmapStruct *edb_msg_parser( ProgramContextStruct *pcs, mempool_t *pool, const char *preamble, size_t item_count, edb_net_item_t *items )
{
	edbParseContext parse_ctx;
	int i, x;
	
	parse_ctx.pcs = pcs;
	parse_ctx.in_item_count = item_count;
	parse_ctx.in_items = items;
	
	
	
	parse_ctx.out_items = cmap_new(pool);

	parse_ctx.parseError = 0;
	parse_ctx.parseErrorStr = NULL;

	x = 0;
	do
	{
		void *parser = (void *)edbParserAlloc(malloc);

		i = 0;
		/* we are operating on an item, it is the responsibility of whoever
		 * is using the item to ensure that current_in_item < item_count: */
		 
		parse_ctx.current_in_item = x;	
//		printf("*** Current Item %d ***\n", x );
		while( preamble[i] != 0 )
		{
			int token_len;
			int token_type;
			Token token;	
			
			token_len = edb_getToken((unsigned char*)&preamble[i],&token_type);
			token.z = (unsigned char *)&preamble[i];
			token.n = token_len;

			switch( token_type )
			{
			case TK_SPACE:
			case TK_COMMENT:
				break;
			case TK_ILLEGAL:
				break;
			case TK_SEMI:
			default:
				edbParser(parser, token_type, token, &parse_ctx );
				break;
			}

			if( parse_ctx.parseError )
			{
				printf("error near \"%s\" (token type: %d): %s\n", &preamble[i], token_type, (parse_ctx.parseErrorStr!=NULL?parse_ctx.parseErrorStr: "") );
				break;
			}
			i += token_len;
		}
		
		edbParserFree( parser, free );
		x++;
	} while( x < item_count );
	
//	mempool_describe(parse_ctx.out_items->mempool);

	return parse_ctx.out_items;
}


